package cn.fl.carloan.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.api.ISysRegionApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.comm.facade.framework.dto.SysRegionDTO;
import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.api.ISysUsrQueryApiService;
import cmm.user.facade.system.constant.SysUsrSysRConstant;
import cmm.user.facade.system.dto.SysOrgDTO;
import cmm.user.facade.system.dto.SysRefUsrDTO;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.carloan.service.IOdrClueInfoService;
import cn.fl.carloan.transform.OdrClueInfoVOTransform;

import cn.fl.carloan.vo.OdrClueInfoVO;
import cn.fl.customer.transform.CstBscInfoVOTransform;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.system.constant.SysLogConstant;

import com.alibaba.fastjson.JSON;
import fl.carloan.facade.carloan.api.IOdrClueInfoApiService;
import fl.carloan.facade.carloan.api.IOdrCstMgrRegionRApiService;
import fl.carloan.facade.carloan.condition.OdrClueInfoQC;
import fl.carloan.facade.carloan.constant.OdrBscInfoConstant; 
import fl.carloan.facade.carloan.constant.OdrCommonConstant;
import fl.carloan.facade.carloan.constant.OdrShopClueInfoConstant;
import fl.carloan.facade.carloan.dto.OdrClueInfoDTO;
import fl.carloan.facade.carloan.enums.OdrStsCdEnums;
import fl.customer.facade.customer.api.ICustomerApiService;
import fl.customer.facade.customer.dto.CstBscInfoDTO;
import fl.flow.facade.flow.api.IFlowQueryApiService;
import fl.flow.facade.flow.condition.SysFlowSHQueryCondition;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.SysFlowSHDTO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 线索线索表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class OdrClueInfoServiceImpl implements IOdrClueInfoService {
    @Autowired
    private IFlowQueryApiService flowQueryApiService;

    @Autowired
    private IOdrClueInfoApiService odrClueInfoApiService;


    @Autowired
    private ICustomerApiService customerApiService;


    @Autowired
    private ISysUsrApiService sysUsrApiService;

    @Autowired
    private ISysOrgApiService sysOrgApiService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Autowired
    private ISysUsrQueryApiService sysUsrQueryApiService;

    @Autowired
    private ISysRegionApiService sysRegionApiService;

    @Autowired
    IOdrCstMgrRegionRApiService odrCstMgrRegionRApiService;


    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(IOdrClueInfoService.class);


    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * TODO 自定义 API 暴露服务
     */

    //@Autowired
    //private I自定义ApiService 自定义ApiService;
    @Override
    public OdrClueInfoVO selectById(Long id) throws BaseException {
        List<Long> idList = null;
        if (StringUtils.isEmpty(id)) {
            BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "获取对象主键不能为空!");
        }
        Map<String, String> genderCdMap = sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_GRP_GENDER_CD); //性别
        OdrClueInfoDTO dto = this.odrClueInfoApiService.selectById(id);

        //贷款金额
        Long contAmt = dto.getContAmt();
        double div1 = DecimalUtils.div(DecimalUtils.convertFenToYuan(contAmt), 10000);


        //购车金额
        Long invoiceAmt = dto.getInvoiceAmt();
        //购车金额
        double div = DecimalUtils.div(DecimalUtils.convertFenToYuan(invoiceAmt), 10000);
        OdrClueInfoVO vo = OdrClueInfoVOTransform.toVO(dto);
        //用户信息
        if (StringUtils.isNotEmpty(vo.getUsrId())) {
            SysUsrDTO usrDto = sysUsrApiService.selectSysUsrById(vo.getUsrId(), CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
            if (usrDto != null) {
                vo.setUsrMp(usrDto.getMp());
            }
        }
        //购车金额
        vo.setMoney(div);
        //贷款金额
        vo.setDkMoney(div1);

        //客户及配偶信息
        if (StringUtils.isNotEmpty(vo.getCstId())) {
            CstBscInfoDTO cstdto = this.customerApiService.selectCstBscInfoDetailById(vo.getCstId(),
                    CurrentThreadContext.getCurrentSysCd(),
                    CurrentThreadContext.getCurrentOrgCd(),
                    CurrentThreadContext.getCurrentBuOrgCd());
            if (cstdto != null) {
                vo.setCstBscInfoVO(CstBscInfoVOTransform.toVO(cstdto));
            } else {
                vo.setCstBscInfoVO(new CstBscInfoVO());
            }
            if (genderCdMap.containsKey(cstdto.getCstNpBscInfoDTO().getGenderCd())) {
                vo.setSex(genderCdMap.get(cstdto.getCstNpBscInfoDTO().getGenderCd()));
            }
        }

        //推荐人信息
        List<Long> refUsrList = new ArrayList<Long>();
        refUsrList.add(vo.getUsrId());
        List<SysRefUsrDTO> sysRefUsrDTOs = this.sysUsrQueryApiService.searchRefUsrInfoListUp(refUsrList, OdrBscInfoConstant.SYS_CD, SysUsrSysRConstant.REF_USR_BUS_TYP_1);
        List<Long> refUsrOneIds = new ArrayList<>();
        List<Long> refUsrTwoIds = new ArrayList<>();
        List<Long> usrIds = new ArrayList<>();
        for (SysRefUsrDTO sysRefUsrDTO : sysRefUsrDTOs) {
            if (null != sysRefUsrDTO.getRefUsrOneId()) {
                Long refUsrOneId = sysRefUsrDTO.getRefUsrOneId();
                refUsrOneIds.add(refUsrOneId);
            }
            if (null != sysRefUsrDTO.getRefUsrTwoId()) {
                Long refUsrTwoId = sysRefUsrDTO.getRefUsrTwoId();
                refUsrTwoIds.add(refUsrTwoId);
            }
        }
        usrIds.addAll(refUsrOneIds);
        usrIds.addAll(refUsrTwoIds);
        if (CollectionUtils.isNotEmpty(usrIds) || usrIds.size() > 0) {
            List<SysUsrDTO> sysUsrDTOS = sysUsrApiService.selectSysUsrList(usrIds);
            for (SysUsrDTO sysUsrDTO : sysUsrDTOS) {
                Long userId = sysUsrDTO.getId();
                if (refUsrOneIds.contains(userId)) {
                    vo.setOneMp(sysUsrDTO.getMp());
                }
                if (refUsrTwoIds.contains(userId)) {
                    vo.setTwoMp(sysUsrDTO.getMp());
                }
            }
        }

        //省名称
        if (vo.getRgnPrCd() != null) {
            SysRegionDTO prRegion = this.sysRegionApiService.getRegionByRgnCd(vo.getRgnPrCd(), CurrentThreadContext.getCurrentSysCd());
            if (prRegion != null) {
                vo.setRgnPrCd(prRegion.getRgnNm());
            }
        }
        //市名称
        if (vo.getRgnCyCd() != null) {
            SysRegionDTO cyRegion = this.sysRegionApiService.getRegionByRgnCd(vo.getRgnCyCd(), CurrentThreadContext.getCurrentSysCd());
            if (cyRegion != null) {
                vo.setRgnCyCd("/" + cyRegion.getRgnNm());
            }
        }
        vo.setClueId(vo.getId() + "");
        return vo;
    }

    @Override
    public Long add(OdrClueInfoVO entity) throws BaseException {
        if (null == entity) {
            BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
            return null;
        }
        //return this.odrClueInfoApiService.add(OdrClueInfoVOTransform.toDTO(entity));
        //TODO 业务逻辑
        return null;
    }

    @Override
    public boolean removeById(Long id) throws BaseException {
        if (StringUtils.isEmpty(id)) {
            BaseLogUtils.info(logger, "removeById", "删除主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
            return false;
        }
        //return this.odrClueInfoApiService.removeById(id);
        //TODO 业务逻辑
        return false;
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids) throws BaseException {
        if (CollectionUtils.isEmpty(ids)) {
            BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
            return false;
        }
        ;
        return false;
    }

    @Override
    public boolean modify(OdrClueInfoVO entity) throws BaseException {
        if (null == entity) {
            BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
            return false;
        }
        if (null == entity.getId()) {
            BaseLogUtils.info(logger, "modify", "修改对象ID不能为空!", CurrentThreadContext.getCurrentUserName());
            return false;
        }
        OdrClueInfoDTO voToDto = OdrClueInfoVOTransform.toDTO(entity);
        
        /*
        OdrClueInfoDTO odrClueInfoDTO = this.odrClueInfoApiService.selectById(entity.getId());
        if (StringUtils.isEmpty(odrClueInfoDTO.getCstNm())) {
            BaseLogUtils.info(logger, "modify", "信息不完整，姓名、身份证号为空时不可操作!", CurrentThreadContext.getCurrentUserName());
            return false;
        }
        
        Long creditRcdId = null;
        // 第一次点击已操作,如果线索记录中征信记录ID为空，则需要进行征信预查询
        if("5".equals(entity.getClueStsCd()) && null == odrClueInfoDTO.getCreditRcdId() && StringUtils.isNotBlank(odrClueInfoDTO.getCstNm())){
        	creditRcdId = updateOdrClueCredit(entity.getId());
        }
        
        if(creditRcdId != null){
        	voToDto.setCreditRcdId(creditRcdId);
        }
        */

        boolean modifyResult = this.odrClueInfoApiService.modify(voToDto);
        return modifyResult;
    }

    @Override
    public Pager searchListPage(Pager page) throws BaseException {
        if (null == page) {
            page = new Pager();
        } else {
            //推荐人查询条件转换为用户ID list
            OdrClueInfoQC qc = (OdrClueInfoQC) page.getCondition();
            List<Long> uList = new ArrayList<Long>();
            Map<Long, Long> uMap = new HashMap<Long, Long>();
            if (StringUtils.isNotEmpty(qc.getFirstUsrNm())) {
                List<Long> usrIdList = new ArrayList<Long>(1);
                usrIdList.add(Long.valueOf(qc.getFirstUsrNm()));
                //根据一级推荐人的id向下查询用户的信息
                List<SysRefUsrDTO> sysRefUsrDTOs = this.sysUsrQueryApiService.searchRefUsrInfoListDown(usrIdList, OdrBscInfoConstant.SYS_CD, SysUsrSysRConstant.REF_USR_BUS_TYP_1);
                if (CollectionUtils.isNotEmpty(sysRefUsrDTOs)) {
                    for (SysRefUsrDTO dto : sysRefUsrDTOs) {
                        if (uMap != null && !uMap.containsKey(dto.getRefUsrOneId())) {
                            uList.add(dto.getRefUsrOneId());
                            uMap.put(dto.getRefUsrOneId(), dto.getRefUsrOneId());
                        }
                    }
                }
            }
            if (StringUtils.isNotEmpty(qc.getSecondUsrNm())) {
                List<Long> usrIdList = new ArrayList<Long>(1);
                usrIdList.add(Long.valueOf(qc.getSecondUsrNm()));
                List<SysRefUsrDTO> sysRefUsrDTOs = this.sysUsrQueryApiService.searchRefUsrInfoListDown(usrIdList, OdrBscInfoConstant.SYS_CD, SysUsrSysRConstant.REF_USR_BUS_TYP_1);
                if (CollectionUtils.isNotEmpty(sysRefUsrDTOs)) {
                    for (SysRefUsrDTO dto : sysRefUsrDTOs) {
                        if (uMap != null && !uMap.containsKey(dto.getRefUsrTwoId())) {
                            uList.add(dto.getRefUsrTwoId());
                            uMap.put(dto.getRefUsrTwoId(), dto.getRefUsrTwoId());
                        }
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(uList)) {
                //将获取的推荐人的id
                qc.setUsrIdList(uList);
                page.setCondition(qc);
            }
        }
        page = this.odrClueInfoApiService.searchOdrAndProjectInfoListPage(page,
                CurrentThreadContext.getCurrentSysCd(),
                CurrentThreadContext.getCurrentOrgCd());
        List<OdrClueInfoDTO> odrClueInfoDTOList = (List<OdrClueInfoDTO>) page.getResultList();
        if (CollectionUtils.isNotEmpty(odrClueInfoDTOList)) {
            this.setDictionaryOption(odrClueInfoDTOList, CurrentThreadContext.getCurrentSysCd(),
                    CurrentThreadContext.getCurrentOrgCd());
            this.setOdrBscInfoOrgInfo(odrClueInfoDTOList, CurrentThreadContext.getCurrentSysCd(),
                    CurrentThreadContext.getCurrentOrgCd());
            List<OdrClueInfoVO> voList = OdrClueInfoVOTransform.toVOList(odrClueInfoDTOList);

            //线索状态字典(转化状态的展示)
            BaseLogUtils.info(logger, "searchClueList", "线索状态，请求参数：" + JSON.toJSONString(OdrCommonConstant.CODE_GRP_CD_CLUE));
            Map<String, String> clueStsMap = this.sysDictionaryApiService.searchGroupToMap(OdrCommonConstant.SYS_CD, OdrCommonConstant.ORG_CD, OdrCommonConstant.CODE_GRP_CD_CLUE);
            Map<String, String> dateResCdMap = sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), OdrShopClueInfoConstant.ODR_CLUE_RES_STS_CD);//车抵贷数据来源

            List<Long> usrIdList = new ArrayList<Long>();
            Map<Long, String> ref1Map = new HashMap<>();
            Map<Long, String> ref2Map = new HashMap<>();
            if (CollectionUtils.isNotEmpty(voList)) {
                for (OdrClueInfoVO vo : voList) {
                    vo.setDateResCdNm(dateResCdMap.get(vo.getResCd()));
                    if (StringUtils.isNotEmpty(vo.getUsrId())) {
                        usrIdList.add(vo.getUsrId());
                    }
                    //转化状态的名称
                    vo.setClueStsCdNm(clueStsMap.get(vo.getClueStsCd()));
                    //将时间字段格式化
                    vo.setCrtTmString(simpleDateFormat.format(vo.getCrtTm()));
                }
                List<SysRefUsrDTO> sysRefUsrDTOs = this.sysUsrQueryApiService.searchRefUsrInfoListUp(usrIdList, OdrBscInfoConstant.SYS_CD, SysUsrSysRConstant.REF_USR_BUS_TYP_1);

                for (OdrClueInfoVO odrClueInfoVO : voList) {
                    Long usrId1 = odrClueInfoVO.getUsrId();
                    for (SysRefUsrDTO sysRefUsrDTO : sysRefUsrDTOs) {
                        Long usrId = sysRefUsrDTO.getUsrId();
                        if (Objects.equals(usrId, usrId1)) {
                            odrClueInfoVO.setRefOneId(sysRefUsrDTO.getRefUsrOneId());
                            odrClueInfoVO.setRefTwoId(sysRefUsrDTO.getRefUsrTwoId());
                        }
                    }

                }

                List<Long> refUsrOneIds = new ArrayList<>();
                List<Long> refUsrTwoIds = new ArrayList<>();
                List<Long> usrIds = new ArrayList<>();
                for (SysRefUsrDTO sysRefUsrDTO : sysRefUsrDTOs) {
                    if (null != sysRefUsrDTO.getRefUsrOneId()) {
                        Long refUsrOneId = sysRefUsrDTO.getRefUsrOneId();
                        refUsrOneIds.add(refUsrOneId);
                    }
                    if (null != sysRefUsrDTO.getRefUsrTwoId()) {
                        Long refUsrTwoId = sysRefUsrDTO.getRefUsrTwoId();
                        refUsrTwoIds.add(refUsrTwoId);
                    }
                }
                usrIds.addAll(refUsrOneIds);
                usrIds.addAll(refUsrTwoIds);
                if (CollectionUtils.isNotEmpty(usrIds) || usrIds.size() > 0) {
                    List<SysUsrDTO> sysUsrDTOS = sysUsrApiService.selectSysUsrList(usrIds);
                    for (OdrClueInfoVO vo : voList) {
                        for (SysUsrDTO sysUsrDTO : sysUsrDTOS) {
                            Long userId = sysUsrDTO.getId();
                            if (Objects.equals(userId, vo.getRefOneId())) {
                                vo.setOneMp(sysUsrDTO.getMp());
                            }
                            if (Objects.equals(userId, vo.getRefTwoId())) {
                                vo.setTwoMp(sysUsrDTO.getMp());
                            }
                        }
                    }
                }


               /* if (CollectionUtils.isNotEmpty(sysRefUsrDTOs)) {
                    for (SysRefUsrDTO sysRefUsrDTO : sysRefUsrDTOs) {
                        if (sysRefUsrDTO.getRefUsrOneId() != null) {
                            ref1Map.put(sysRefUsrDTO.getUsrId(), (sysRefUsrDTO.getRefUsrOneRlNm() == null ? "未实名" : sysRefUsrDTO.getRefUsrOneRlNm()) + sysRefUsrDTO.getRefUsrOneId());
                        }
                        if (sysRefUsrDTO.getRefUsrTwoId() != null) {
                            ref2Map.put(sysRefUsrDTO.getUsrId(), (sysRefUsrDTO.getRefUsrTwoRlNm() == null ? "未实名" : sysRefUsrDTO.getRefUsrTwoRlNm()) + sysRefUsrDTO.getRefUsrTwoId());
                        }
                    }
                }
                for (OdrClueInfoVO vo : voList) {
                    if (ref1Map != null && ref1Map.containsKey(vo.getUsrId())) {
                        vo.setRefOneNm(ref1Map.get(vo.getUsrId()));
                    }
                    if (ref2Map != null && ref2Map.containsKey(vo.getUsrId())) {
                        vo.setRefTwoNm(ref2Map.get(vo.getUsrId()));
                    }
                }*/
            }
            page.setResultList(voList);
        }
        return page;
    }

    @Override
    public Long addClueInfo(OdrClueInfoVO odrClueInfoVO) throws BaseException {
        if (null == odrClueInfoVO) {
            BaseLogUtils.info(logger, "addClueInfo", "新增对象不存在!");
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "新增对象不存在!");
        }
        ;
        //根据用户Id查询推荐人Id
        SysUsrDTO sysUsrDTO = sysUsrApiService.selectSysUsrById(odrClueInfoVO.getUsrId(), OdrCommonConstant.SYS_CD, OdrCommonConstant.ORG_CD);
        if (null != sysUsrDTO) {
            odrClueInfoVO.setUsrLoginMp(sysUsrDTO.getMp());
            String refRefUsrId = sysUsrDTO.getRefRefUsrId();
            if (StringUtils.isNotEmpty(refRefUsrId)) {
                odrClueInfoVO.setRcdId(Long.valueOf(refRefUsrId));
            }
        }
        //如果有客户ID 根据客户Id 查询客户名称
        if (StringUtils.isNotEmpty(odrClueInfoVO.getCstId())) {
            CstBscInfoDTO cstBscInfoDTO = customerApiService.selectCstBscInfoById(odrClueInfoVO.getCstId(), OdrCommonConstant.ORG_CD);
            if (null != cstBscInfoDTO) {
                odrClueInfoVO.setCstNm(cstBscInfoDTO.getCstNm());
            }
        }
        OdrClueInfoDTO odrClueInfoDTO = OdrClueInfoVOTransform.toDTO(odrClueInfoVO);

        return this.odrClueInfoApiService.addClueInfo(odrClueInfoDTO);
    }


    @Override
    public List<OdrClueInfoDTO> searchClueList(OdrClueInfoQC odrClueInfoQC) {
        if (null == odrClueInfoQC) {
            BaseLogUtils.info(logger, "searchClueList", "参数不能为空!", CurrentThreadContext.getCurrentUserName());
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "获取对象不能为空!");
        }
        List<OdrClueInfoDTO> odrBscInfoResultDTOS = odrClueInfoApiService.searchClueList(odrClueInfoQC);

        //线索状态字典
        BaseLogUtils.info(logger, "searchClueList", "线索状态，请求参数：" + JSON.toJSONString(OdrCommonConstant.CODE_GRP_ODR_STS_CD));
        Map<String, String> odrStsMap = this.sysDictionaryApiService.searchGroupToMap(OdrCommonConstant.SYS_CD, OdrCommonConstant.ORG_CD, OdrCommonConstant.CODE_GRP_ODR_STS_CD);
        BaseLogUtils.info(logger, "searchClueList", "线索状态，返回结果：" + JSON.toJSONString(odrStsMap));

        for (OdrClueInfoDTO odrBscInfoResultDTO : odrBscInfoResultDTOS) {
            if (Integer.parseInt(odrBscInfoResultDTO.getClueStsCd()) > 6) {
                odrBscInfoResultDTO.setClueStsCd(OdrStsCdEnums.reservation_success.code);
            }
            odrBscInfoResultDTO.setContAmtD(DecimalUtils.convertFenToYuan(odrBscInfoResultDTO.getContAmt()));
            odrBscInfoResultDTO.setClueStsCdNm(odrStsMap.get(odrBscInfoResultDTO.getClueStsCd()));
        }
        return odrBscInfoResultDTOS;
    }

    @Override
    public boolean setCstToOdrClue(OdrClueInfoVO odrClueInfoVO) {

        if (null == odrClueInfoVO) {
            BaseLogUtils.info(logger, "setCstToOdrClue", "操作不存在!");
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "操作不存在!");
        }
        ;
        //如果有客户ID 根据客户Id 查询客户名称
        if (StringUtils.isNotEmpty(odrClueInfoVO.getCstId())) {
            CstBscInfoDTO cstBscInfoDTO = customerApiService.selectCstBscInfoById(odrClueInfoVO.getCstId(), OdrCommonConstant.ORG_CD);
            if (null != cstBscInfoDTO) {
                odrClueInfoVO.setCstNm(cstBscInfoDTO.getCstNm());
            }
        }
        return odrClueInfoApiService.modifyClueInfo(OdrClueInfoVOTransform.toDTO(odrClueInfoVO));
    }

    @Override
    public List<KeyValueVO> searchCdList(String grpCd) {
        return this.getKvList(grpCd);
    }

    private void setDictionaryOption(List<OdrClueInfoDTO> list, String sysCd, String orgCd) {
        Map<String, String> prjTypCdMap = sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_PRJ_TYPE_CD); //项目类型名称
        Map<String, String> bizTypCdMap = sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_PRJ_BIZ_TYP_CD);//业务类型名称
        Map<String, String> dateResCdMap = sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, OdrBscInfoConstant.CODE_SYS_DS_CD);//车抵贷数据来源
        Map<String, String> prjStsMap = sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, DictionaryConstant.CODE_AUD_STS_CD);//项目状态
        Map<String, SysDictionaryDTO> odrStsCdMap = sysDictionaryApiService.searchGroupToObjMap(sysCd, orgCd, OdrBscInfoConstant.ODR_STS_CD);//预约状态

        List<Long> prjidList = new ArrayList<Long>();
        List<Long> cstIdList = new ArrayList<Long>();
        List<Long> usrIdList = new ArrayList<Long>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (OdrClueInfoDTO odrBscInfoDTO : list) {

                prjidList.add(odrBscInfoDTO.getId());
                cstIdList.add(odrBscInfoDTO.getCstId());
                usrIdList.add(odrBscInfoDTO.getUsrId());
                //数据来源
                if (null != odrBscInfoDTO.getDateResCd()) {
                    if (dateResCdMap.containsKey(odrBscInfoDTO.getDateResCd())) {
                        odrBscInfoDTO.setDataResNm(dateResCdMap.get(odrBscInfoDTO.getDateResCd()));
                    }
                }
                if (null != odrBscInfoDTO.getClueStsCd()) {
                    if (odrStsCdMap.containsKey(odrBscInfoDTO.getClueStsCd())) {
                        if (StringUtils.isNotEmpty(odrStsCdMap.get(odrBscInfoDTO.getClueStsCd()).getCodeAttr1())) {
                            odrBscInfoDTO.setOdrStsCdNm(odrStsCdMap.get(odrBscInfoDTO.getClueStsCd()).getCodeAttr1());
                        } else if (StringUtils.isNotEmpty(odrStsCdMap.get(odrBscInfoDTO.getClueStsCd()).getCodeAttr2())) {
                            odrBscInfoDTO.setOdrStsCdNm(odrStsCdMap.get(odrBscInfoDTO.getClueStsCd()).getCodeAttr2());
                        } else {
                            odrBscInfoDTO.setOdrStsCdNm(odrStsCdMap.get(odrBscInfoDTO.getClueStsCd()).getCodeNm());
                        }
                    }
                }


            }
            List<String> busTypList = new ArrayList<String>();
            Map<Long, SysFlowSHDTO> flowMap = new HashMap<Long, SysFlowSHDTO>();
            if (CollectionUtils.isNotEmpty(prjidList)) {
                SysFlowSHQueryCondition qc = new SysFlowSHQueryCondition();
                qc.setDataIdList(prjidList);
                qc.setWordsInTheTable("PRJ");
                qc.setSysCd(sysCd);
                busTypList.add(FlowConstant.FLOW_MODEL_TYP_PRJ_1);
                qc.setBusTypList(busTypList);
                qc.setStatus(BaseConstant.IS_YESNO_YES);
              /*  List<SysFlowSHDTO> flowSHList = this.flowQueryApiService.searchFlowSHList(qc);
                if (CollectionUtils.isNotEmpty(flowSHList)) {
                    for (SysFlowSHDTO sysFlowSHDTO : flowSHList) {
                        if (!flowMap.containsKey(sysFlowSHDTO.getDataId())) {
                            flowMap.put(sysFlowSHDTO.getDataId(), sysFlowSHDTO);
                        }
                    }
                }*/
            }
        }
    }

    /**
     * 设置组织架构名称
     *
     * @param listDTO
     * @param sysCd
     * @param orgCd
     */
    private void setOdrBscInfoOrgInfo(List<OdrClueInfoDTO> listDTO, String sysCd, String orgCd) {
        List<SysOrgDTO> list = this.sysOrgApiService.searchSysOrgListBy(CurrentThreadContext.getCurrentSysCd());
        Map<String, SysOrgDTO> buOrgCdMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (SysOrgDTO sysOrgDTO : list) {
                buOrgCdMap.put(sysOrgDTO.getOrgCd(), sysOrgDTO);
            }
        }
        SysOrgDTO sysOrgDTO = null;
        //设置组织架构名称
        for (OdrClueInfoDTO odrClueInfoDTO : listDTO) {
            if (StringUtils.isEmpty(odrClueInfoDTO.getCstMgrOrgCd())) return;
            String codeNm = "";
            if (null != odrClueInfoDTO.getBuOrgCd()) {
                codeNm = this.sysOrgApiService.selectSysOrgNmByOrgCd(odrClueInfoDTO.getBuOrgCd(), sysCd);
                odrClueInfoDTO.setBuOrgCdNm(codeNm);
            }

            if (buOrgCdMap.containsKey(odrClueInfoDTO.getCstMgrOrgCd())) {
                sysOrgDTO = buOrgCdMap.get(odrClueInfoDTO.getCstMgrOrgCd());
                odrClueInfoDTO.setCstMgrOrgCdNm(sysOrgDTO.getOrgNm());
                orgCd = sysOrgDTO.getOrgCd();
                while (orgCd.length() > 8) {
                    if ("4".equals(sysOrgDTO.getOrgTypCd())) {//分公司
                        odrClueInfoDTO.setCyOrgCdNm(sysOrgDTO.getOrgNm());
                    } else if ("3".equals(sysOrgDTO.getOrgTypCd())) {
                        odrClueInfoDTO.setPrOrgCdNm(sysOrgDTO.getOrgNm());
                        break;
                    }
                    orgCd = orgCd.substring(0, orgCd.length() - 4);
                    if (buOrgCdMap.containsKey(orgCd)) {
                        sysOrgDTO = buOrgCdMap.get(orgCd);
                    } else {
                        break;
                    }
                }
            }
        }

    }


    /**
     * 根据字典中代码组值获取组员集合
     *
     * @param grpCd 代码组值
     * @return 集合
     */
    private List<KeyValueVO> getKvList(String grpCd) {
        List<KeyValueVO> kvList = new ArrayList<>();
        try {
            List<SysDictionaryDTO> sysDictionaryDTOList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), grpCd);
            if (CollectionUtils.isNotEmpty(sysDictionaryDTOList)) {
                for (SysDictionaryDTO sysDictionaryDTO : sysDictionaryDTOList) {
                    KeyValueVO keyValueVO = new KeyValueVO();
                    keyValueVO.setKey(sysDictionaryDTO.getCode());
                    keyValueVO.setValue(sysDictionaryDTO.getCodeNm());
                    kvList.add(keyValueVO);
                }
            }
        } catch (BaseException e) {
            BaseLogUtils.info(logger, "getKvList", "获取字典项组" + grpCd + "失败.ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception e) {
            BaseLogUtils.error(logger, "getKvList", "获取字典项组" + grpCd + "失败,系统错误.ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return kvList;
    }


    @Override
    public String exportOdrClueInfoDetail(OdrClueInfoQC qc, String sysCd, String orgCd) {
        if (qc == null) {
            qc = new OdrClueInfoQC();
        }
        String path = this.odrClueInfoApiService.exportOdrClueInfoDetail(qc, sysCd, orgCd);
        //  "/var/www/html/attachments/11000/odrclueinfo/20181204/XS20181204135418.xlsx"
        path = path.replace(PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH), PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH));
        //  "http://10.20.7.115:80/attachments/11000/odrclueinfo/20181204/XS20181204135418.xlsx"
        return path;
    }


    /**
     * 检查重要自然人信息项
     *
     * @param cstNm
     * @param certNo
     */
    private void checkCstVIDInfoItemNp(String cstNm, String certNo) {

        if (StringUtils.isBlank(cstNm) || cstNm.length() > 20 || !StringUtils.isCustomerName(cstNm)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, SysLogConstant.LOG_CUST_VALID_CST_NM);
        }

        if (StringUtils.isBlank(certNo)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, SysLogConstant.LOG_CUST_VALID_CERT_NO_EMPTY);
        }

        if (!StringUtils.isIdCardNumber(certNo)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, SysLogConstant.LOG_CUST_VALID_CERT_NO_ERROR);
        }


    }

	
	/*
	@Override
	public Long updateOdrClueCredit(Long clueId) throws BaseException {
		if(StringUtils.isEmpty(clueId)){
			BaseLogUtils.info(logger, "updateOdrClueCredit", "更新线索用户征信，线索ID不允许为空!");
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "更新线索用户征信，线索ID不允许为空!");
		}
		
        OdrClueInfoDTO odrClueInfoDTO = this.odrClueInfoApiService.selectById(clueId);
        // 如果存在征信ID，但是没有征信结果，则不进行查询，等待定时任务同步征信结果
        Long dbCreditRcdId = odrClueInfoDTO.getCreditRcdId();
        Date creditMdfTm = odrClueInfoDTO.getCreditMdfTm();
        if(dbCreditRcdId != null && creditMdfTm == null){
        	BaseLogUtils.info(logger, "updateOdrClueCredit", "更新线索用户征信：线索用户[线索Id="+clueId+"]征信ID已存在，等待查询中");
        	throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "征信ID已存在，等待查询中");
        }
        // 如果存在征信结果，并且时间在2个月以内，则不进行更新操作
        if(creditMdfTm != null && DateUtils.before(DateUtils.getDateAddDate(creditMdfTm, 2, 2), new Date())){
        	BaseLogUtils.info(logger, "updateOdrClueCredit", "更新线索用户征信：线索用户[线索Id="+clueId+"]征信等级已存在，默认2个月内不可重复查询征信");
        	throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "征信结果过期(默认2个月有效期)方可重新查询!");
        }
    	
    	//校验客户姓名、身份证信息
    	checkCstVIDInfoItemNp(cstNm, certNo);
    	CstValidCardInfoVO cstValidCardInfoVO = this.odrBscInfoService.validateCstCert(cstNm, certNo);
    	if (!cstValidCardInfoVO.getSuccess()) {
            //第三方验证未通过
            String info = "客户身份信息验证失败! certNm:" + cstNm + " - certNo:" + certNo;
            BaseLogUtils.info(logger, "modify", info, CurrentThreadContext.getCurrentUserName());
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "客户身份信息验证失败!");
        }
    	
    	RcCstBscInfoDTO rcCstBscInfoDTO = new RcCstBscInfoDTO();
    	rcCstBscInfoDTO.setCstMgrId(odrClueInfoDTO.getCstMgrId());
    	rcCstBscInfoDTO.setCstMgrNm(odrClueInfoDTO.getCstMgrNm());
    	rcCstBscInfoDTO.setCstMgrOrgCd(odrClueInfoDTO.getCstMgrOrgCd());
    	rcCstBscInfoDTO.setCstMgrBuOrgCd(odrClueInfoDTO.getBuOrgCd());
    	rcCstBscInfoDTO.setCstNm(odrClueInfoDTO.getCstNm());
    	rcCstBscInfoDTO.setCstTypCd(CustomerConstant.CST_TYP_CD_NP); 		//自然人
    	rcCstBscInfoDTO.setCertTypCd(CustomerConstant.CODE_CERT_TYP_CD_A);  //证件类型-身份证
    	rcCstBscInfoDTO.setDsCd(odrClueInfoDTO.getDateResCd());
    	rcCstBscInfoDTO.setCrtUsrId(odrClueInfoDTO.getUsrId());
    	rcCstBscInfoDTO.setCrtNm(odrClueInfoDTO.getCstNm());
    	
    	String certNo = null;	//证件号   130627199110024621
    	String mp1 = null;		//手机号   null
        //客户及配偶信息
        if (StringUtils.isNotEmpty(odrClueInfoDTO.getCstId())) {
            CstBscInfoDTO cstdto = this.customerApiService.selectCstBscInfoDetailById(odrClueInfoDTO.getCstId(),
                    CurrentThreadContext.getCurrentSysCd(),
                    CurrentThreadContext.getCurrentOrgCd(),
                    CurrentThreadContext.getCurrentBuOrgCd());
            if (cstdto != null) {
            	certNo = cstdto.getCertNo();
            	mp1 = cstdto.getMp1();
            }
        }
    	
    	String phone = null;		//手机号    15100333333
    	String refCertNo = null;	//证件号    null
        if(StringUtils.isNotEmpty(odrClueInfoDTO.getUsrId())){
        	//用户信息
        	SysUsrDTO usrDto = sysUsrApiService.selectSysUsrById(odrClueInfoDTO.getUsrId(),CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
            if(usrDto!=null){
            	phone = usrDto.getMp();
            	refCertNo = usrDto.getRefCertNo();
            }
        }
        //rcCstBscInfoDTO.setCertNo(certNo);
    	rcCstBscInfoDTO.setCertNo(refCertNo != null ? refCertNo : certNo);
    	rcCstBscInfoDTO.setMp1(phone);
    	
    	String hostAddress = null;
    	try {
			hostAddress = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			BaseLogUtils.error(logger, "updateOdrClueCredit", "获取IP",e);
		}
    	 //新增征信
        BaseLogUtils.info(logger,"addCarLoan","新增征信，请求参数："+JSON.toJSONString(rcCstBscInfoDTO));
        //征信记录ID
        Long creditRcdId = null;
        try {
        	creditRcdId = this.carLoanAddApiService.addCarLoan(rcCstBscInfoDTO, hostAddress);   //181205296001606
		} catch (InterruptedException e) {
			BaseLogUtils.error(logger, "addCarLoan", "新增征信：添加风险基础信息", e);
			e.printStackTrace();
		}
        BaseLogUtils.info(logger, "modify", "新增征信，返回结果： rcCstBscInfoId = " + creditRcdId);
		
		return creditRcdId;
	}
	 */

	
	/*
	@Override
	public boolean searchWhetherHasCreditTest() throws BaseException {
		boolean result = this.odrClueInfoApiService.searchWhetherHasCredit();
		return result;
	}*/

}
